IF EXISTS ( SELECT * FROM sysobjects WHERE name = 'SaveCfgCtrl' AND type = 'P' AND uid = 1 )
     DROP PROCEDURE dbo.SaveCfgCtrl
GO

CREATE PROCEDURE dbo.SaveCfgCtrl
     @CfgCtrlKey            varchar(30), 
     @CfgCtrlValue          varchar(8000),
     @CfgCtrlDescription    varchar(128) = NULL, -- Optional entry
     @SuppressResultsetFlag tinyint      = 0
AS
/*
 *
 * SaveCfgCtrl
 *
 * Purpose:      To Add and update records to the CfgCtrl table.
 *
 * Inputs:       
 *
 * Assumes:      CfgCtrl table exists
 *
 * Effects:      Records are inserted or updated in CfgCtrl
 *
 * Returns:      CfgCtrlKey, CfgCtrlDescription, and CfgCtrlValue
 *
 * Calling
 * Application:  
 *
 * Note(s):      Post change values are returned for app verification of save.
 *
 *               The description, once written cannot be changed here.
 *
 * Author(s):    NOVA Concepts Ltd.
 *
 * Change Log:   Initial Release, 01/06/2012, 1.00.0000
 *
 */
BEGIN
     SET NOCOUNT ON
     SET XACT_ABORT ON

     IF ( @CfgCtrlKey IS NULL ) 
     BEGIN
          RAISERROR( 'CfgCtrlKey must be specified.', 16, 1 )
     END
     ELSE
     BEGIN -- We got a value
          IF EXISTS ( SELECT 'X' FROM dbo.CfgCtrl WHERE CfgCtrlKey = @CfgCtrlKey )
          BEGIN -- Update
               UPDATE dbo.CfgCtrl
               SET    LastModDt    = CURRENT_TIMESTAMP,
                      CfgCtrlValue = LTRIM( RTRIM( @CfgCtrlValue ) )
               FROM   dbo.CfgCtrl
               WHERE  CfgCtrlKey = @CfgCtrlKey
          END
          ELSE
          BEGIN -- Insert
               INSERT dbo.CfgCtrl
                    ( CfgCtrlKey, 
                      CfgCtrlDescription, 
                      CfgCtrlValue )
               SELECT LTRIM( RTRIM( @CfgCtrlKey ) ),
                      ISNULL( LTRIM( RTRIM( @CfgCtrlDescription ) ), 'Unspecified' ),
                      LTRIM( RTRIM( @CfgCtrlValue ) )
          END
     END

     -- Output results if allowed
     IF ( @SuppressResultsetFlag != 1 )
     BEGIN
          SELECT CfgKey         = LTRIM( RTRIM( CfgCtrlKey ) ),
                 CfgDescription = LTRIM( RTRIM( CfgCtrlDescription ) ),
                 CfgValue       = LTRIM( RTRIM( CfgCtrlValue ) )
          FROM   dbo.CfgCtrl
          WHERE  CfgCtrlKey = @CfgCtrlKey
     END
END
GO
